<?php

namespace App\Http\Models\Business;

use App\Http\Models\Base\PayerCategory;
use App\Http\Models\BaseModel;
use Exception;

class Payer extends BaseModel
{
    protected $table = 'payer';
    public $year = 0;
    protected $fillable = ['code', 'name', 'category_code'];

    //结果数据， 键名为 品类id, 键值为 规模金额
    public $payer_scale_result = [];

    //结果数据， 键名为 品类id, 键值为数组 ['quantity' => 0, 'amount' => 0, 'normal_amount' => 0]
    public $payer_z1_scale_result = [];

    public function payer_category()
    {
        return $this->belongsTo(PayerCategory::class, 'category_code', 'code');
    }


    //设置客户规模结果数据
    public function setPayerScaleResultForSave(array $data)
    {
        foreach ($data as $value) {
            if (array_key_exists($value['category_contract_id'], $this->payer_scale_result)) {
                $this->payer_scale_result[$value['category_contract_id']] += $value['amount'];
            } else {
                $this->payer_scale_result[$value['category_contract_id']] = $value['amount'];
            }
        }
    }

    //设置客户规模结果数据
    public function setPayerZ1ScaleResultForSave(array $data)
    {
        foreach ($data as $value) {
            if (!array_key_exists($value['category_contract_id'], $this->payer_z1_scale_result)) {
                $this->payer_z1_scale_result[$value['category_contract_id']] = ['quantity' => 0, 'amount' => 0, 'normal_amount' => 0];
            }
            foreach ($value as $field_name => $field_val) {
                if ($field_name == 'category_contract_id') {
                    continue;
                }
                $this->payer_z1_scale_result[$value['category_contract_id']][$field_name] += $field_val;
            }
        }
    }

    public function saveCachePayerScaleData()
    {
        if ($this->year == 0)
            throw new Exception('需要保存的客户规模数据没有设置年份！');

        if (count($this->payer_scale_result) == 0)
            return;

        foreach ($this->payer_scale_result as $category_contract_id => $amount) {
            CachePayerScale::updateOrCreate(
                ['year' => $this->year, 'payer_code' => $this->code, 'category_contract_id' => $category_contract_id],
                ['amount' => $amount]
            );
        }
    }

    public function saveCachePayerZ1ScaleData()
    {
        if ($this->year == 0)
            throw new Exception('需要保存的客户规模数据没有设置年份！');

        if (count($this->payer_z1_scale_result) == 0)
            return;

        foreach ($this->payer_z1_scale_result as $category_contract_id => $value) {
            CachePayerZ1Scale::updateOrCreate(
                ['year' => $this->year, 'payer_code' => $this->code, 'category_contract_id' => $category_contract_id],
                ['quantity' => $value['quantity'], 'amount' => $value['amount'], 'normal_amount' => $value['normal_amount']]
            );
        }
    }
}
